package com.lrkj.back.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.lrkj.back.service.TbEmployeeService;
import com.lrkj.back.service.TbModuleService;
import com.lrkj.back.service.TbPackageMubanService;
import com.lrkj.back.service.ZsYicipinKucunService;
import com.lrkj.back.vo.KucunWarnVO;
import com.lrkj.back.entity.TbEmployee;
import com.lrkj.back.entity.TbModule;
import com.lrkj.back.entity.TbPackageMuban;
import com.lrkj.back.entity.ZsPackageImformation;
import com.lrkj.back.Const;
import com.lrkj.back.CreateMD5;
import com.lrkj.back.service.TbEmpOperService;
import com.lrkj.back.service.TbShiftService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lrkj.back.entity.TbDepartment;
import com.lrkj.back.entity.TbEmpOper;
import com.lrkj.back.entity.TbShift;
import com.lrkj.back.entity.ZsDabao;
import com.lrkj.back.entity.ZsYicipinKucun;
import com.lrkj.back.entity.ZsYicipinRukumingxi;
import com.lrkj.back.service.TbDepartmentService;
import com.lrkj.back.service.TbSeqService;
import com.lrkj.back.service.ZsPackageImformationService;
import com.lrkj.back.service.ZsYicipinRukumingxiService;
import cn.com.cbons.mamisay.parent.exception.BusinessException;

import com.github.pagehelper.PageInfo;


@Controller
@RequestMapping("/employee")// 访问的前缀
public class TbEmployeeController extends BaseController{
	@Autowired//自动寻找的注解
	private TbEmployeeService tbEmployeeService;
	@Autowired//部门查询
	private TbDepartmentService tbDepartmentService;
	@Autowired
	private TbSeqService seqService;
	@Autowired
	private TbModuleService moduleService;
	@Autowired
	private TbEmpOperService empOperService;
	@Autowired
	private TbShiftService shiftService;
	@Autowired
	private ZsYicipinRukumingxiService rukumingxiService;
	@Autowired
	private ZsPackageImformationService packageInfoService;
	@Autowired
	private ZsYicipinKucunService ycpKucunService;
	@Autowired
	private TbPackageMubanService packagemubanService;

	@RequestMapping(value="/login.do",method = RequestMethod.POST)
	@ResponseBody
	public Map<Object,Object> login(HttpServletRequest request,
			HttpServletResponse response) throws BusinessException, IOException, ParseException{
		Map<Integer,List<TbModule>> menuList = new HashMap<>();
		List<TbModule> firstMenu = new ArrayList<>();
		Map<Object ,Object> modelMap = new HashMap<>();
		Map<String ,Object> shiftMap = new HashMap<>();
		String employeeLoginname = request.getParameter("username");
		String employeePassword = request.getParameter("password");
		String outMsg = "";
		boolean islogin = false;
		if(StringUtils.isBlank(employeeLoginname)){
			outMsg = "用户名不为空";
		}else if(StringUtils.isBlank(employeeLoginname)){
			outMsg = "密码不为空";
		}else{
			TbEmployee tep = tbEmployeeService.findEmployeeByEmployeeLoginname(employeeLoginname);
			if(tep !=null ){
				if(CreateMD5.getMd5(employeePassword).equals(tep.getEmployeePassword())){
					//登录成功，基本信息设定
					islogin = true;
					request.getSession().setAttribute("emp", tep);
					request.getSession().setAttribute("empId", tep.getEmployeeId());
					request.getSession().setAttribute("empDId", tep.getDepartmentId());
					//所有的权限
					if(tep.getEmployeeSuper()==1){
						List<TbModule> modules = moduleService.findAdminModule();
						for(TbModule module : modules){
							if(menuList.containsKey(module.getModuleParent())){
								menuList.get(module.getModuleParent()).add(module);
							}else{
								List<TbModule> moduleList = new ArrayList<>();
								moduleList.add(module);
								menuList.put(module.getModuleParent(), moduleList);
								TbModule rootmodule = moduleService.selectByPrimaryKey(module.getModuleParent());
								firstMenu.add(rootmodule);
							}
						}
					}else{
						Map<String, Object> operMap = new HashMap<>();
						operMap.put("employeeId", tep.getEmployeeId());
						List<TbEmpOper> empOperList = empOperService.findAllTbEmpOper(operMap);
						Collections.sort(empOperList);
						for(TbEmpOper eo : empOperList){
							TbModule module = moduleService.selectByPrimaryKey(eo.getModuleId());
							Integer moduleParent = module.getModuleParent()!=null?module.getModuleParent():5;
							if(menuList.containsKey(moduleParent)){
								menuList.get(moduleParent).add(module);
							}else{
								List<TbModule> moduleList = new ArrayList<>();
								moduleList.add(module);
								menuList.put(moduleParent, moduleList);
								TbModule rootmodule = moduleService.selectByPrimaryKey(module.getModuleParent());
								firstMenu.add(rootmodule);
							}
						}
					}
					shiftMap.put("shiftSort", 2);
					TbShift shift = shiftService.findOne(shiftMap);
//					String lujing = shift.getShiftImg().replace(shift.getShiftImg().lastIndexOf("."), 4);
					/*FileInputStream fis=new FileInputStream(shift.getShiftTitle());
					byte[] byt=new byte[fis.available()];
					String txt=new String(byt);*/
					Collections.sort(firstMenu);
					Object json = JSON.toJSON(menuList);
					System.out.print(json);
					request.getSession().setAttribute("shift", shift);
					request.getSession().setAttribute("menuList", json);
					request.getSession().setAttribute("firstMenu", firstMenu);
				}else{
					outMsg = "密码错误";
				}
			}else{
				outMsg = "用户不存在";
			} 
		}
		modelMap.put("status", islogin);
		modelMap.put("msg", outMsg);

		// ajax 请求的返回数据
		return modelMap;
	}


	/**
	 * 带条件的分页查询
	 * @param request
	 * @param response
	 * @return
	 */
	//首页--人员管理   （点击查询）
	@RequestMapping(value="/empList.do")
	public ModelAndView empList(String searchTxt,HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Integer pageNo = request.getParameter("pageIndex")==null? 1 :Integer.valueOf(request.getParameter("pageIndex"));
		Map<String,Object> map =new HashMap<String,Object>();
		if(StringUtils.isNotBlank(searchTxt)){
			map.put("employeeName", searchTxt);
			map.put("employeeTel", searchTxt);
			map.put("employeeLoginname", searchTxt);
		}
		map.put("pageNo", pageNo);
		map.put("pageSize", Const.PAGE_SIZE);
		PageInfo<TbEmployee> page = tbEmployeeService.queryTbEmployeeList(map);
		for(TbEmployee emp : page.getList()){
			Integer departmentId = emp.getDepartmentId();
			if(emp.getDepartmentId()==null){
				departmentId = 0;
			}
			emp.setDepartment(tbDepartmentService.selectByPrimaryKey(String.valueOf(departmentId)));
		}
		request.setAttribute("empList", page.getList());
		request.setAttribute("searchTxt", searchTxt==null?"":searchTxt);
		request.setAttribute("total", page.getPages());
		return new ModelAndView("/system/yuangongguanli/emp_list");
	}
	//添加时用到的方法
	@RequestMapping("/empEdit.do")
	public ModelAndView empEdit(Integer id, HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		TbEmployee emp = (id == null) ? new TbEmployee() : tbEmployeeService.selectByPrimaryKey(id);
		Map<String, Object> operMap = new HashMap<>();
		if(id == null){
//			SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMdd");
//			String empno = "EMP"+sdf.format(new Date())+seqService.seqVal("employeeno");
			String empno = "EMP"+seqService.seqVal("employeeno");
			emp.setEmployeeNo(empno);
			operMap.put("employeeId", "0");
		} else if (id != null){
			operMap.put("employeeId", id);
		}
		List<TbDepartment> departmentList = tbDepartmentService.findAllDepartment();
		request.setAttribute("departmentList", departmentList);
		Map<Integer,TbEmpOper> eoMap = new HashMap<>();
		TbDepartment depart = tbDepartmentService.selectByPrimaryKey(String.valueOf(emp.getDepartmentId()));
		emp.setDepartment(depart);
		request.setAttribute("emp", emp);
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("moduleParent", "all");
		List<TbModule> tbModuleList = moduleService.findAllTbModules(paramMap);
		List<TbEmpOper> empOperList = empOperService.findAllTbEmpOper(operMap);
		for(TbEmpOper empOrder : empOperList){
			eoMap.put(empOrder.getModuleId(), empOrder);
		}
		List<TbModule> treeModule = new ArrayList<>();
		Map<Integer,List<TbModule>> treemap = new HashMap<>();
		for(TbModule module : tbModuleList){
			if(module.getModuleParent() == null){
				treeModule.add(module);
			}else{
				List<TbModule> list = treemap.get(module.getModuleParent());
				if(list == null){
					list = new ArrayList<>();
				}
				if(eoMap.containsKey(module.getModuleId())){
					module.setChecked("checked");
				}
				list.add(module);
				treemap.put(module.getModuleParent(), list);
			}
		}
		request.setAttribute("treeModule", treeModule);
		request.setAttribute("treeMap", treemap);
		
		return new ModelAndView("/system/yuangongguanli/emp_edit");
	}
	
	@RequestMapping("/editInfo.do")
	public ModelAndView editInfo(HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		TbEmployee emp = (TbEmployee)request.getSession().getAttribute("emp");
		if(StringUtils.isEmpty(emp.getEmployeePic())){
			emp.setEmployeePic("");
		}else{
			emp.setEmployeePic(request.getContextPath()+emp.getEmployeePic());
		}
		request.setAttribute("emp", emp);
		return new ModelAndView("/page/updinfo");
	}

	private static int getAgeByBirth(Date birthday) {
		int age = 0;
		try {
			Calendar now = Calendar.getInstance();
			now.setTime(new Date());// 当前时间

			Calendar birth = Calendar.getInstance();
			birth.setTime(birthday);

			if (birth.after(now)) {//如果传入的时间，在当前时间的后面，返回0岁
				age = 0;
			} else {
				age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
				if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
					age += 1;
				}
			}
			return age;
		} catch (Exception e) {//兼容性更强,异常后返回数据
			return 0;
		}
	}
	
	@RequestMapping(value="/empSave.do")
	@ResponseBody
	public Map<Object,Object> empSave( TbEmployee employee)throws BusinessException, IOException{
		Date date = employee.getEmployeeBirthday();
		int age = getAgeByBirth(date);
		employee.setEmployeeAge(age);
		Map<Object, Object> rtnMap = new HashMap<>();
		String password = employee.getEmployeePassword();
		String psword = "";
		try {
			if(employee.getEmployeeId()!=null){
				TbEmployee employee1 = tbEmployeeService.selectByPrimaryKey(employee.getEmployeeId());
				psword = employee1.getEmployeePassword();

			}
			if(StringUtils.isNotBlank(password)&&!password.equals(psword)){

				employee.setEmployeePassword(CreateMD5.getMd5(employee.getEmployeePassword()));
			}
			if(employee.getEmployeeId() == null ){
				employee.setEmployeeCreatetime(new Date());
				employee = tbEmployeeService.insert(employee);
			}else{
				
				tbEmployeeService.updateByPrimaryKeySelective(employee);
			}			
			//设置权限
			String[] modules = request.getParameterValues("key");
			empOperService.deleteByEmpId(employee.getEmployeeId());
			TbEmpOper eo = null;
			for(String id:modules){
				eo = new TbEmpOper();
				eo.setEmployeeId(employee.getEmployeeId());
				eo.setEmpoperCreatetime(new Date());
				eo.setModuleId(Integer.valueOf(id));
				empOperService.insert(eo);
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
	@RequestMapping(value="/empDelete.do")
	@ResponseBody
	public Map<Object,Object> empDelete(HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Map<Object ,Object> rtnMap = new HashMap<>();
		String id =  request.getParameter("id");
		String[] ids= id.split(",");
		try {
			for(String tid :ids){
				tbEmployeeService.deleteByPrimaryKey(Integer.valueOf(tid));
				empOperService.deleteByEmpId(Integer.valueOf(tid));
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "删除成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "删除失败");
			e.printStackTrace();
		}
		return rtnMap;
	}

	//密码修改
	@RequestMapping(value="/mimaUpdate.do")
	@ResponseBody
	public Map<Object,Object> mimaUpdate(HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
				
		Map<Object ,Object> rtnMap = new HashMap<Object,Object>();
		try {
			String username =  request.getParameter("username");
			String password=  request.getParameter("password");
			String newpassword =  request.getParameter("newpassword");		
			System.out.println(username+"***"+password+"**"+newpassword);
			TbEmployee emp = new TbEmployee();
			//CreateMD5.getMd5(employee.getEmployeePassword())			
			emp.setEmployeeLoginname(username );
			emp.setEmployeePassword(CreateMD5.getMd5(password));//加密
			TbEmployee st = tbEmployeeService.queryMima(emp);//验证密码
			if(st!=null){
				System.out.println("存在");
				TbEmployee emp2 = new TbEmployee();
				emp2.setEmployeeLoginname(username);
				emp2.setEmployeePassword(CreateMD5.getMd5(newpassword));
				tbEmployeeService.updateEmpPassword(emp2);
				rtnMap.put("status", "true");
				rtnMap.put("msg", "修改成功");
			}else{
				System.out.println("不存在");
				rtnMap.put("status", "false");
				rtnMap.put("msg", "修改失败"); 
			}	
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "修改失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
	@RequestMapping("mimaupdate.do")
	public ModelAndView mimaupdate(HttpServletRequest request, HttpServletResponse response)throws BusinessException{
		return new ModelAndView("/system/yuangongguanli/mima_update");
	}
	
	@RequestMapping("empXiangqing.do")
	public ModelAndView empXiangqing(String id, HttpServletRequest request, HttpServletResponse response)throws BusinessException{
		Map<String, Object> map = new HashMap<>();
		TbEmployee employee = tbEmployeeService.selectByPrimaryKey(Integer.valueOf(id));
		map.put("employeeId", employee.getEmployeeId());
		List<TbEmpOper> empOpers = empOperService.findAllTbEmpOper(map);
		List<Integer> moduleIdList = new ArrayList<>();
		for (TbEmpOper tbEmpOper : empOpers) {
			if (!moduleIdList.contains(tbEmpOper.getModuleId())) {
				moduleIdList.add(tbEmpOper.getModuleId());
			}
		}
		if (!moduleIdList.isEmpty()) {
			map.put("moduleIdArr", moduleIdList);
		}else {
			moduleIdList.add(0);
			map.put("moduleIdArr", moduleIdList);
		}
		List<TbModule> modules = moduleService.findAllTbModules(map);
		request.setAttribute("module", modules);
		request.setAttribute("emp", employee);
		return new ModelAndView("system/yuangongguanli/emp_xiangqing");
	}
	
	@RequestMapping("findByTioma.do")
	@ResponseBody
	public Map<Object,Object> findByTiaoma(String id, HttpServletRequest request, HttpServletResponse response)throws BusinessException{
	    Map<Object, Object> rtnMap = new HashMap<Object, Object>();
	    TbEmployee employee = null;
	    if (StringUtils.isNotBlank(id)) {
	    	employee = tbEmployeeService.selectByEmployeeNo(id);
		}
	    if (employee != null ) {
	    	rtnMap.put("statue", "true");
	    	rtnMap.put("msg", "扫码成功");
		}else {
	    	rtnMap.put("statue", "false");
	    	rtnMap.put("msg", "扫码失败");
		}
		return rtnMap;
	}
	

	
	@RequestMapping("check.do")
	@ResponseBody
	public Map<Object,Object> checkDate() throws ParseException, BusinessException{
		Map<String,Object> map =new HashMap<>();
		Map<Object,Object> rtnMap =new HashMap<>();
//		TbEmployee employee = (TbEmployee)session.getAttribute("emp");
		long oneday = 24*60*60*1000;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowtime = sdf.format(date);
		//得到的是当前的时间
		long nowDate = sdf.parse(nowtime).getTime();
		String str = "";
		//-------------------查询过期提醒--------------------------------
		//===================查询过期提醒(一次品)从入库明细表中查
		List<ZsYicipinRukumingxi> ycprRukumingxis = rukumingxiService.findAllNoPage(map);
		if (!ycprRukumingxis.isEmpty()) {
			Date shixiaoDate = null;
			for (ZsYicipinRukumingxi zsYicipinRukumingxi : ycprRukumingxis) {
				shixiaoDate = addDate(zsYicipinRukumingxi.getRukuCreatetime(), zsYicipinRukumingxi.getProductYouxiaoqiDays());
			    if (shixiaoDate.getTime()-nowDate <= 2*oneday) {
			    	str += "有一次品即将过期,";
			    	break;
				}
			}
		}
		//===================查询过期提醒(包)
//		Map<String, Object> map = new HashMap<String,Object>();
		map.put("baoRuku", 1);
		map.put("shoushu", "weifafang");
		//只针对通用包
		//配包关包时间，开始计算包有效期
		List<ZsPackageImformation> packageImformations = packageInfoService.findAll(map);
		//循环     一个包一个包的判断
		if (!packageImformations.isEmpty()) {
			ZsDabao dabao = null;
			Integer youxiaoqi = null;
			long shixiaoriqi = 0l;
			String guanbaotime = "";
			for (ZsPackageImformation zsPackageImformation : packageImformations) {
				//得到包的有效期
				dabao = zsPackageImformation.getTbPackageMuban().getZsDabao();
				if (dabao!=null) {
				    youxiaoqi = dabao.getDabaoYouxiaoqiDays();
				}
				//得到包的有效期
				guanbaotime = sdf.format(zsPackageImformation.getPeibaoGuanbaoTime());
				//包的失效日期
				shixiaoriqi = sdf.parse(guanbaotime).getTime()+youxiaoqi*oneday+oneday/2;
				//得到当前日期
				long danqian = nowDate;
				//得到失效日期与当前日期的时间差
				long timecha = shixiaoriqi-danqian;
				if (timecha<=2*oneday) {
					str += "有包即将过期,";
			    	break;
				}
				
			}
		}
		//-----------------------库存预警-----------------------------------------
		//=======================库存预警(一次品)
		//一次品库存数量的提醒标准
		map.put("SYkucun", 15);
		List<ZsYicipinKucun> ycpKucuns = ycpKucunService.findYicipinKucun(map);
		if (!ycpKucuns.isEmpty()) {
			str += "一次品库存不足,";
		}
		//=======================库存预警(包)
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("packageCategory", 1);
		//查找所有通用包模板
		List<TbPackageMuban> packageMubans = packagemubanService.findAllPackageNoPageList(map2);
		List<Integer> mubanIds = new ArrayList<Integer>();
		for (TbPackageMuban tbPackageMuban : packageMubans) {
			if (!mubanIds.contains(tbPackageMuban.getPackageId())) {
				mubanIds.add(Integer.valueOf(tbPackageMuban.getPackageId()));
			}
		}
		if (!mubanIds.isEmpty()) {
			map2.put("packageIdArr", mubanIds);
		}else {
			mubanIds.add(0);
			map2.put("packageIdArr", mubanIds);
		}
		map2.put("baoRuku", 1);
		map2.put("shoushu", "shengyubao");
		List<KucunWarnVO> kucunWarnVOs2 = packageInfoService.findRestbao(map2);
		if (!kucunWarnVOs2.isEmpty()) {
			str += "包库存不足,";
		}
	    rtnMap.put("str", str);
		return rtnMap;
	}
	
	public static Date addDate(Date date,long day) throws ParseException,BusinessException {
		long time = date.getTime(); // 得到指定日期的毫秒数
		day = day*24*60*60*1000; // 要加上的天数转换成毫秒数
		time+=day; // 相加得到新的毫秒数
		return new Date(time); // 将毫秒数转换成日期
	}
}